package cn.zh.org.service.impl;

import cn.zh.base.eum.ShopStateEnum;
import cn.zh.base.query.BaseQuery;
import cn.zh.base.service.impl.BaseServiceImpl;
import cn.zh.base.util.BaiduAuditUtils;
import cn.zh.base.util.BusinessException;
import cn.zh.base.util.PageList;
import cn.zh.org.domain.Employee;
import cn.zh.org.domain.Shop;
import cn.zh.org.domain.ShopAuditLog;
import cn.zh.org.dto.ShopAdminDto;
import cn.zh.org.dto.ShopAuditDto;
import cn.zh.org.dto.ShopSettlementDto;
import cn.zh.org.mapper.EmployeeMapper;
import cn.zh.org.mapper.ShopAuditLogMapper;
import cn.zh.org.mapper.ShopMapper;
import cn.zh.org.service.IShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zh
 * @since 2023-02-28
 */
@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {

    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private ShopAuditLogMapper auditLogMapper;
    @Autowired
    private JavaMailSender javaMailSender;
    @Override
    public void settlement(ShopSettlementDto dto) {
        Long id = dto.getId();
        if (dto.getId() == null && "".equals(dto.getId())) {
            this.verify(dto);
            this.save(dto);
        } else {
//            // 根据店铺名称去查询
//            Shop shop = shopMapper.findByName(dto.getName());
//            if (shop != null) {
//                throw new BusinessException("店铺已存在，请直接登录");
//            }
//            // 根据用户名称去查询用户数据
//            if (!BaiduAuditUtils.TextCensor(dto.getName())) {
//                throw new BusinessException("店铺名字违规");
//            }
//            if (!"".equals(dto.getLogo()) && dto.getLogo() != null) {
//                if (!BaiduAuditUtils.ImgCensor(dto.getLogo())) {
//                    throw new BusinessException("logo违规");
//                }
//            }
            this.update(dto);
        }
    }

    @Override
    public void auditPass(ShopAuditDto dto) {
        Shop shop = new Shop();
        shop.setId(dto.getShopId());
        shop.setState(1);//ShopStateEnum.WAIT_ACTIVE.getCode()
        shopMapper.update(shop);
        ShopAuditLog shopAuditLog = new ShopAuditLog();
        shopAuditLog.setShopId(dto.getShopId());
        shopAuditLog.setAuditId(-1);
        shopAuditLog.setNote(dto.getNote());
        shopAuditLog.setAuditTime(new Date());
        auditLogMapper.add(shopAuditLog);
        try {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
        helper.setFrom("573567075@qq.com");
        helper.setSubject("宠物乐园审核结果通知");
        // 3.设置文本内容，第二个参数 true 代表是否是一个html内容
        helper.setText("<h1>恭喜你审核通过：请点击下方链接激活店铺：</h1>"+
                "http://localhost:8080/shop/activity/"+dto.getShopId(),true);
        // 4.添加附件
//            helper.addAttachment("好东西.jpg",new File("C:\\Users\\admin\\Desktop\\1.jpg"));
        // 5.设置收件人
        helper.setTo("573567075@qq.com");
        // 6.发送邮件
        javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void activity(Long id) {
        Shop shop = new Shop();
        shop.setId(id);
        shop.setState(2);
        shopMapper.update(shop);
    }

    @Override
    public void auditReject(ShopAuditDto dto){
        Shop shop = new Shop();
        shop.setId(dto.getShopId());
        shop.setState(3);
        shopMapper.update(shop);
        ShopAuditLog shopAuditLog = new ShopAuditLog();
        shopAuditLog.setShopId(dto.getShopId());
        shopAuditLog.setAuditId(-1);
        shopAuditLog.setNote(dto.getNote());
        shopAuditLog.setAuditTime(new Date());
        auditLogMapper.add(shopAuditLog);
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "utf-8");
            helper.setFrom("573567075@qq.com");
            helper.setSubject("宠物乐园审核结果通知");
            // 3.设置文本内容，第二个参数 true 代表是否是一个html内容
            helper.setText("<h1>很遗憾您未通过审核：请点击下方链接重新申请入驻：</h1>" +
                    "http://localhost:8081/#/RegisterAgain?id=" + dto.getShopId(), true);
            // 4.添加附件
//            helper.addAttachment("好东西.jpg",new File("C:\\Users\\admin\\Desktop\\1.jpg"));
            // 5.设置收件人
            helper.setTo("573567075@qq.com");
            // 6.发送邮件
            javaMailSender.send(mimeMessage);
        } catch (MessagingException ex) {
            ex.printStackTrace();
        }
    }

    private void verify(ShopSettlementDto dto) {
        // 1.参数校验
        // 1.5手机号验证
//        Pattern p = Pattern.compile("^[1][3,4,5,7,8][0-9]{9}$"); // 验证手机号
//        Matcher m = p.matcher(dto.getAdmin().getPhone());
//        if (!m.matches()){
//            throw new BusinessException("用户手机号格式不正确！");
//        }
        // 2.两次密码是否一致
        ShopAdminDto admin = dto.getAdmin();
        if (!admin.getPassword().equals(admin.getComfirmPassword())) {
            throw new BusinessException("两次密码不一致");
        }
        // 3.店铺是否注册过
        // 根据店铺名称去查询
        Shop shop = shopMapper.findByName(dto.getName());
        if (shop != null) {
            throw new BusinessException("店铺已存在，请直接登录");
        }
        // 4.当前管理员是否已经管理店铺
        // 根据用户名称去查询用户数据
        Employee emp = employeeMapper.findByName(admin.getUsername());
        if (emp != null && emp.getShopId() != null) {
            Shop shop1 = shopMapper.findByAdminId(emp.getId());
            if (shop1 != null) {
                throw new BusinessException("该用户已注册过请，请重新注册");
            }
        }
        if (!BaiduAuditUtils.TextCensor(dto.getName())) {
            throw new BusinessException("店铺名字违规");
        }
        if (!"".equals(dto.getLogo()) && dto.getLogo() != null) {
            if (!BaiduAuditUtils.ImgCensor(dto.getLogo())) {
                throw new BusinessException("logo违规");
            }
        }
    }

    private void update(ShopSettlementDto dto) {
        // 添加数据
        // 把dto的字段取出来赋值给shop对象
        Shop shop = dto.getShop();
        // 添加emp对象
        // 把dto的字段取出来赋值给shop对象
//        Employee emp = dto.getEmp();
//        emp.setShopId(shop.getId());
//        employeeMapper.update(emp);
//        Shop shop1 = new Shop();
//        shop.setAdminId(emp.getId());
        shopMapper.update(shop);
    }

    private void save(ShopSettlementDto dto) {
        // 添加数据
        // 把dto的字段取出来赋值给shop对象
        Shop shop = dto.getShop();
        shopMapper.add(shop);
        // 添加emp对象
        // 把dto的字段取出来赋值给shop对象
        Employee emp = dto.getEmp();
        emp.setShopId(shop.getId());
        employeeMapper.add(emp);
        Shop shop1 = new Shop();
        shop1.setId(shop.getId());
        shop1.setAdminId(emp.getId());
        shopMapper.update(shop1);
    }

    @Override
    public PageList<Shop> queryByPage(BaseQuery query) {
        PageList<Shop> list = super.queryByPage(query);
        List<Shop> rows = list.getRows();
        List<Long> shopIds = rows.stream().map(Shop::getId).collect(Collectors.toList());
        List<ShopAuditLog> logs = auditLogMapper.findByShopIds(shopIds);
        Map<Long, List<ShopAuditLog>> map = logs.stream().collect(Collectors.groupingBy(ShopAuditLog::getShopId));
        rows.stream().forEach(shop -> {
            shop.setShopAuditLogs(map.get(shop.getId()));
        });
//        list.setRows(rows);
        return list;
    }
}
